import { Input, InputProps } from '@tarojs/components';
import { FC, ReactNode, useCallback, useEffect, useRef, useState } from 'react';

import './index.scss';

interface OurInputProps extends InputProps {
  label: string | ReactNode;
  rule?: RegExp;
  showError?: boolean;
  commitError?: (name: string, errType?: 'empty' | 'invalid') => void;
  onChange?: (e: string) => void;
}

const OurInput: FC<OurInputProps> = (props) => {
  const [isFocus, setIsFocus] = useState(false);
  const [value, setValue] = useState('');
  const [isError, setIsError] = useState(false);
  const iptRef = useRef<HTMLInputElement | null>(null);

  const init = useCallback(() => {
    !!props.value && setValue(props.value);
    setIsFocus(!!props.value);
    setIsError(props.showError || false);
    props.commitError && props.commitError(props.name || '', 'invalid');
  }, [props]);

  useEffect(() => {
    init();
  }, [init]);

  const changeValue = (e) => {
    const inputValue = e.detail.value;
    setValue(inputValue);
    if (!props.rule) return;
    if (!props.rule.test(inputValue) && !!inputValue) {
      setIsError(true);
      // 需要收集错误时传入name作为标识
      props.commitError && props.commitError(props.name || '', 'invalid');
    } else {
      setIsError(false);
      console.log(inputValue, '?????');
      !!props.onChange && props.onChange(inputValue);
      !inputValue &&
        props.commitError &&
        props.commitError(props.name || '', 'empty');
    }
  };

  const focusInput = () => {
    setIsFocus(true);
    iptRef.current && iptRef.current.focus();
  };

  // 错误处理

  return (
    <div className={props.className || ''}>
      <div
        className={
          'thisInputGroup' +
          (isFocus ? ' focusThisInputGroup' : '') +
          (isError ? ' thisInputHasError' : '')
        }
        onClick={focusInput}
      >
        <Input
          {...props}
          className="thisInput"
          placeholder=""
          ref={iptRef}
          value={value}
          onFocus={() => setIsFocus(true)}
          onInput={changeValue}
          onBlur={() => setIsFocus(!!value)}
        />
        <div className="thisInputOthers">
          <div className="bar">
            <p className="barLineError barLine" />
            <p className="barLineLeft barLine" />
            <p className="barLineRight barLine" />
          </div>
          <label className="thisLabel">{props.label}</label>
        </div>
      </div>
    </div>
  );
};

export default OurInput;
